﻿using System;
using System.Collections.Generic;

namespace DatabaseStuff.Basic
{
    /// <summary>
    /// Basic implementation of a record in a database.
    /// THIS CLASS NEEDS RESTRUCTURING BY USE OF A IREADONLYDICTIONARY
    /// </summary>
    public class Record: DatabaseStuff.IDBRecord
    {
        private class DataSet : HashMap<Field, DBData>
        {
            public DataSet()
                : base()
            { }

            public DataSet(IDictionary<Field, DBData> _records)
                : base(_records)
            { }

            protected override Field GetKeyFromValue(DBData value)
            {
                return value.Field;
            }
        }

        private Table table;
        private DataSet contents;

        public Record(Table _table)
        {
            table = _table;
            contents = new DataSet();
        }

        /// <summary>
        /// DI-Compatible Constructor
        /// </summary>
        /// <param name="_dict"></param>
        /// <param name="_table"></param>
        internal Record(IDictionary<Field, DBData> _dict, Table _table)
        {
            table = _table;
            contents = new DataSet(_dict);
        }

        public Table Table
        {
            get { return table; }
        }

        public ICollection<DBData> Contents
        {
            get { return contents; }
        }

        IDBTable DatabaseStuff.IDBRecord.Table
        {
            get { return table; }
        }

        IEnumerable<IDBData> DatabaseStuff.IDBRecord.Contents
        {
            get { return contents; }
        }

        public DBData this[IDBField field]
        {
            get
            {
                Field f = field as Field;

                if (f == null)
                    throw new ArgumentException("Could not convert the parameter to an instance of the database field implementation class");

                return contents[f];
            }
        }

        IDBData DatabaseStuff.IDBRecord.this[IDBField field]
        {
            get
            {
                return this[field];
            }
        }

        /// <summary>
        /// NEEDS IMPROVEMENT - INEFFICIENT
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public DBData this[string fieldName]
        {
            get
            {
                foreach (DBData data in contents.Values)
                {
                    if (data.Field.Name.Equals(fieldName))
                        return data;
                }

                throw new ArgumentException("Could not find data matching the specified field name");
            }
        }
    }
}
